import { lrc } from "./lrc.js";


const domList = {
  audio: document.querySelector('audio'),
  ul: document.querySelector('ul'),
  rightWrapper: document.querySelector('.right-wrapper'),
}
const centerHeight = domList.rightWrapper.clientHeight / 2;
let startScrollHeight = 0;
let isScroll = false;

/**
 * 解析歌词字符串, 得到歌词的对象数组
 * 每个歌词对象： { time: 时间, words: 歌词内容 }
 */
const parseLrcStrToList = () => {
  const lineList = lrc.split('\n');
  const tempLrcList = [];
  for (let index = 0; index < lineList.length; index++) {
    const item = lineList[index];
    const perLine = item.split(']');
    const timeStr = perLine[0].substring(1);
    const firstChat = timeStr.split('')[0];
    if(!Object.is(Number(firstChat), NaN) && perLine[1] != '') tempLrcList.push({ time: parseTimeStrToSeconds(timeStr), words: perLine[1] }); ;
  }
  return tempLrcList;
}

/**
 * 将时间字符串转为成秒数
 */
const parseTimeStrToSeconds = str => {
    const times = str.split(':');
    return Number(times[0]) * 60 + Number(times[1]);
}

/**
 * 创建li元素
 */
const createLrcLi = lrcList => {
  //创建一个文档片段，用于收集要添加的节点信息，最后统一添加。比每循环一个添加一个效率高，因为统一添加只回流一次。
  const fragUl = document.createDocumentFragment();
  for (let index = 0; index < lrcList.length; index++) {
    const li = document.createElement('li');
    li.textContent = lrcList[index].words;
    fragUl.appendChild(li);
  }
  domList.ul.appendChild(fragUl);
}

/**
 * 按照播放器时间得到对应高亮歌词的index
 */
const findActiveIndex = lrcList => {
  const currentTime = domList.audio.currentTime + 0.5 - 0.2;  //播放器当前时间 + 歌词过渡动画的时间 - 偏移量
  //第一句时间之前的会返回-1
  //最后一句时间之后,结束for循环,直接返回最后一个下标
  for (let index = 0; index < lrcList.length; index++) {
    if(currentTime <= lrcList[index].time) return index - 1;
  }
  return lrcList.length - 1;
}

/**
 * 设置当前播放歌词的偏移量和样式
 */
const setCurrWodsOffsetAndStyle = (activeWordsIndex, lrcList) => {
  //初始偏移量为右侧wrapper高度的一半。偏移值减小，歌词上移。减小的数值是当前歌词之前的歌词的高度之和，所以
  // let preOffset = centerHeight + startScrollHeight;
  console.log('isScroll',isScroll);
  if(!isScroll) {
    let preOffset = startScrollHeight;
    for (let index = 0; index < lrcList.length; index++) if(index < activeWordsIndex) preOffset -= lrcList[index].height;
    domList.ul.style.transform = `translateY(${ preOffset }px)`;
  }

  //移除旧的高亮li样式
  const lastActiveLi = document.querySelector('.active-li');
  lastActiveLi && lastActiveLi.classList.remove('active-li');
  //设置新的高亮li样式
  const li = domList.ul.children[activeWordsIndex];
  li && li.classList.add('active-li');
}

// 滚动动画
const scrollAnimation = scrollHeight => {
  let t;
  // const speed = domList.rightWrapper.scrollTop / 400 * 10; //每毫秒滚动的距离
  const speed = scrollHeight / 400 * 10; //每毫秒滚动的距离
  t = setInterval(() => {
    domList.rightWrapper.scrollTop -= speed;
    // console.log(startScrollHeight, domList.rightWrapper.scrollTop );
    if (domList.rightWrapper.scrollTop >= startScrollHeight - 50 && domList.rightWrapper.scrollTop <= startScrollHeight + 50) {
      clearInterval(t);
      domList.rightWrapper.scrollTop = startScrollHeight;
    }
  }, 10);
}

/**
 * 设置滚动后返回当前歌词处的滚动
 */
const setBackCurrAfterScroll = () => {
  let timer;
  domList.rightWrapper.addEventListener('scroll', e => {
    isScroll = true;
    const scrollHeight = domList.rightWrapper.scrollHeight;
    const scrollTop = domList.rightWrapper.scrollTop;
    const clientHeight = domList.rightWrapper.clientHeight;
    // if (scrollTop + clientHeight == scrollHeight) {
    //   domList.rightWrapper.scrollTo(0,domList.rightWrapper.scrollTop - 10);
    // }
    
    // console.log('scrollBottom', domList.rightWrapper.scrollBottom);
    
    // 可见区域高：document.body.clientHeight
    // 正文全文高：document.body.scrollHeight
    // 当前滚动位置：document.body.scrollTop
    // 当 clientHeight + scrollTop == scrollHeight时滚动到底部

    // 连续滚动清除定时器，重新计时
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      isScroll = false;
      // console.log(scrollTop + clientHeight == scrollHeight)
      if (scrollTop + clientHeight == scrollHeight) scrollAnimation(domList.rightWrapper.scrollTop - startScrollHeight);
      else scrollAnimation(domList.rightWrapper.scrollTop - startScrollHeight);
      // scrollAnimation(domList.rightWrapper.scrollTop - startScrollHeight);
      // domList.rightWrapper.scrollTop = startScrollHeight;
    }, 2000);
  })
}

/**
 * 为歌词的对象数组添加每句歌词的高度,以便计算滚动偏移量
 */
const addPerLiHeight = lrcList => {
  for (let index = 0; index < lrcList.length; index++) {
    lrcList[index].height = domList.ul.children[index].clientHeight;
  }
}

window.check = () => {
  console.log('preOffset',preOffset)
  console.log('domList.rightWrapper.scrollTop',domList.rightWrapper.scrollTop)
}

const main = () => {
  const lrcList = parseLrcStrToList();
  createLrcLi(lrcList);
  addPerLiHeight(lrcList);

  startScrollHeight = Math.floor(domList.ul.scrollHeight / 2);
  domList.rightWrapper.scrollTop = startScrollHeight;
  // console.log('startScrollHeight', startScrollHeight);
  // console.log('offset', centerHeight + startScrollHeight );
  // preOffset = centerHeight + startScrollHeight;
  setBackCurrAfterScroll();
  // domList.ul.style.transform = `translateY(${ centerHeight }px)`;  //设置未播放时的位置。
  domList.ul.style.transform = `translateY(${ startScrollHeight }px)`;  //设置未播放时的位置。
  domList.audio.addEventListener('timeupdate', () => {
    const activeWordsIndex = findActiveIndex(lrcList);
    setCurrWodsOffsetAndStyle(activeWordsIndex, lrcList);
  })
}
main();






